//#include "mplayer.h"

//标准输入输出库函数
#include <stdio.h>
//线程头文件
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

pthread_cond_t cond ;//条件变量 
pthread_mutex_t mutex ;//互斥锁

struct task_node
{
    void (*task)(void*);      //任务函数指针
    void *arg;
    struct task_node *next;   //下一个节点
};

struct task_node *task_head = NULL;   //任务队列头指针

//添加任务到任务队列
void add_task(struct task_node *head, void (*task_a)(void*),void *arg)
{
    struct task_node *new_task = (struct task_node*)malloc(sizeof(struct task_node)); //创建新任务节点
    if(new_task == NULL)
    {
        printf("malloc error\n");
        return ;
    }
    while(head->next != NULL)
    {
        head = head->next;
    }
    new_task->task = task_a;   //插入函数指针
    new_task->arg = arg;

    new_task->next =NULL;
    head->next = new_task; //将新任务添加到任务队列尾部(尾插法)
}

//执行任务线程
void *thread_task(void *arg)
{
    while(1)
    {
        printf("等待任务\n");
        pthread_cond_wait(&cond,&mutex);
        printf("执行任务\n");
        pthread_mutex_unlock(&mutex);
        struct task_node *pos=task_head;
        if(task_head->next == NULL)
        {
            printf("当前无任务\n");
            continue;
        }
        pos=pos->next;

        task_head->next = pos->next;

        pos->task(NULL);

        free(pos);
    }
    

}
void play_music(void*arg)
{
    printf("播放音乐\n");
    sleep(5);
}
void off_music(void*arg)
{
    printf("关闭音乐\n");
    sleep(5);
}
int main()
{
    //初始化任务队列
    task_head = (struct task_node*)malloc(sizeof(struct task_node));
    if(task_head == NULL)
    {
        printf("malloc error\n");
        return -1;
    }
    task_head->next = NULL;
    task_head->task = NULL;

    //初始化条件变量与初始化互斥锁
    pthread_cond_init(&cond,NULL);
    pthread_mutex_init(&mutex,NULL);
    //创建线程
    pthread_t tid[10]={0};
    for(int i=0;i<10;i++)
    {
        pthread_create(&tid[i],NULL,thread_task,NULL);
    }
    int set=0;
    while(1)
    {
        
        scanf("%d",&set);
        if(set == 0)
        {
            break;
        }
        if(set == 1)
        {
            add_task(task_head,play_music,NULL);
        }
        if(set == 2)
        {
            add_task(task_head,off_music,NULL);
        }
        pthread_cond_signal(&cond); //唤醒线程
        
    } 
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
   
    return 0;
}